import 'package:flutter/material.dart';
import 'package:flutter_hsh/fluttergromore/ads/ad_feed_view.dart';
import 'package:flutter_hsh/fluttergromore/ads/ads_utils.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import '../../style/style.dart';
import '../../routes/app_pages.dart';
import 'jilu_logic.dart';

/// 日历记录页面
class JiluPage extends StatefulWidget {
  const JiluPage({super.key});

  @override
  State<JiluPage> createState() => _JiluPageState();
}

class _JiluPageState extends State<JiluPage> {
  final JiluLogic logic = Get.put(JiluLogic());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.blue[50],
     
      body: SafeArea(
        child: Container(
          decoration: const BoxDecoration(
            
          ),
          child: Obx(() => _buildContent()),
        ),
      ),
      // 添加浮动按钮
      floatingActionButton: _buildAddButton(),
    );
  }

  // 构建添加按钮
  Widget _buildAddButton() {
    return FloatingActionButton(
      onPressed: () {
        // 使用路由名称跳转，路由配置中已设置过渡动画
        Get.toNamed(Routes.jiluAdd);
      },
      backgroundColor: const Color(0xFF00C853), // 绿色按钮
      child: const Icon(Icons.add, color: Colors.white, size: 32),
    );
  }

  // 构建内容
  Widget _buildContent() {
    // 说明：根据 showListView 的值切换展示
    // - 日历模式（showListView=false）：保持原有布局（日历 + 当天事项）
    // - 清单模式（showListView=true）：隐藏日历，显示所有记录的列表（含日期、时间）
    return Column(
      children: [
        _buildHeader(),
        SizedBox(height: 16.h),
        if (!logic.showListView.value) ...[
          _buildCalendarContainer(),
          _buildTodoSection(),
        ] else ...[
          Expanded(child: _buildAllRecordsList()),
        ],
      ],
    );
  }

  // 构建头部
  Widget _buildHeader() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // 日期显示
          Text(
            logic.formattedDate,
            style: TextStyle(
              fontSize: 20.sp,
              fontWeight: FontWeight.bold,
              color: Colors.black,
            ),
          ),
          // 视图切换按钮
          Row(
            children: [
              // 清单按钮
              GestureDetector(
                // 选中清单：显式设为清单模式（隐藏日历，展示所有记录）
                onTap: () => logic.setShowListView(true),
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
                  decoration: BoxDecoration(
                    color: logic.showListView.value ? kAppThemeColor : Colors.transparent,
                    borderRadius: BorderRadius.circular(20.r),
                  ),
                  child: Text(
                    '清单',
                    style: TextStyle(
                      fontSize: 16.sp,
                      color: logic.showListView.value ? Colors.white : Colors.black54,
                    ),
                  ),
                ),
              ),
              SizedBox(width: 8.w),
              // 日历图标按钮
              GestureDetector(
                // 选中日历：显式设为日历模式（显示日历与当天事项）
                onTap: () => logic.setShowListView(false),
                child: Container(
                  padding: EdgeInsets.all(8.r),
                  decoration: BoxDecoration(
                    color: !logic.showListView.value ? kAppThemeColor : Colors.transparent,
                    borderRadius: BorderRadius.circular(20.r),
                  ),
                  child: Icon(
                    Icons.calendar_today,
                    color: !logic.showListView.value ? Colors.white : Colors.black54,
                    size: 20.r,
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  // 清单视图：展示所有记录（待办/提醒），按日期时间排序，含日期与时间显示
  Widget _buildAllRecordsList() {
    // 说明：
    // - 使用逻辑层提供的 allTasksSorted（已按日期时间从近到远或从远到近排序）
    // - 每一项展示：日期、时间、类型标签、标题、备注、提醒图标与完成状态
    final allTasks = logic.allTasksSorted;

    if (allTasks.isEmpty) {
      return Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(Icons.inbox_outlined, size: 48.r, color: Colors.grey[300]),
            SizedBox(height: 8.h),
            Text(
              '暂无记录',
              style: TextStyle(fontSize: 14.sp, color: Colors.grey[500]),
            ),
            SizedBox(height: 4.h),
            Text(
              '点击右下角"+"添加记录、提醒或待办',
              style: TextStyle(fontSize: 12.sp, color: Colors.grey[400]),
            ),
          ],
        ),
      );
    }

    return ListView.separated(
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 8.h),
      itemBuilder: (context, index) => _buildRecordListItem(allTasks[index],index),
      separatorBuilder: (_, __) => SizedBox(height: 8.h),
      itemCount: allTasks.length,
    );
  }

  // 清单视图中的单条记录项（包含日期与时间展示）
  Widget _buildRecordListItem(TaskItem task,int index) {
    // 格式化日期与时间
    final dateStr = '${task.dateTime.year.toString().padLeft(4, '0')}-${task.dateTime.month.toString().padLeft(2, '0')}-${task.dateTime.day.toString().padLeft(2, '0')}';
    final timeStr = '${task.dateTime.hour.toString().padLeft(2, '0')}:${task.dateTime.minute.toString().padLeft(2, '0')}';
    if(index == 1){
      return Column(
        children: [
          SizedBox(height: 10.h,),
          const MyAdFeedView(),
          SizedBox(height: 10.h,),
          Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(12.r),
              boxShadow: [
                BoxShadow(color: Colors.black.withOpacity(0.04), blurRadius: 6, offset: const Offset(0, 2)),
              ],
            ),
            child: Material(
              color: Colors.transparent,
              borderRadius: BorderRadius.circular(12.r),
              child: InkWell(
                borderRadius: BorderRadius.circular(12.r),
                onTap: () => logic.toggleTaskCompletion(task.id),
                child: Padding(
                  padding: EdgeInsets.all(12.r),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 左侧：日期与时间
                      Container(
                        width: 86.w,
                        padding: EdgeInsets.symmetric(vertical: 4.h),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              dateStr,
                              style: TextStyle(fontSize: 12.sp, color: Colors.grey[600]),
                            ),
                            SizedBox(height: 4.h),
                            Row(
                              children: [
                                Icon(Icons.access_time, size: 14.r, color: Colors.grey[500]),
                                SizedBox(width: 4.w),
                                Text(
                                  timeStr,
                                  style: TextStyle(fontSize: 12.sp, color: Colors.grey[500]),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),

                      // 右侧：标题、类型标签、备注与状态
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              children: [
                                // 标题
                                Expanded(
                                  child: Text(
                                    task.title,
                                    style: TextStyle(
                                      fontSize: 16.sp,
                                      fontWeight: FontWeight.w500,
                                      color: task.isCompleted ? Colors.grey[500] : Colors.black,
                                      decoration: task.isCompleted ? TextDecoration.lineThrough : TextDecoration.none,
                                    ),
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                ),
                                SizedBox(width: 8.w),
                                // 类型标签
                                Container(
                                  padding: EdgeInsets.symmetric(horizontal: 6.w, vertical: 2.h),
                                  decoration: BoxDecoration(
                                    color: task.typeColor.withOpacity(0.1),
                                    borderRadius: BorderRadius.circular(4.r),
                                    border: Border.all(color: task.typeColor.withOpacity(0.3)),
                                  ),
                                  child: Text(
                                    task.typeName,
                                    style: TextStyle(fontSize: 10.sp, color: task.typeColor, fontWeight: FontWeight.bold),
                                  ),
                                ),
                              ],
                            ),
                            if (task.note.isNotEmpty) ...[
                              SizedBox(height: 4.h),
                              Text(
                                task.note,
                                style: TextStyle(
                                  fontSize: 14.sp,
                                  color: task.isCompleted ? Colors.grey[400] : Colors.grey[600],
                                  decoration: task.isCompleted ? TextDecoration.lineThrough : TextDecoration.none,
                                ),
                                maxLines: 2,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ],
                            SizedBox(height: 6.h),
                            Row(
                              children: [
                                // 完成状态图标
                                Container(
                                  width: 20.r,
                                  height: 20.r,
                                  decoration: BoxDecoration(
                                    shape: BoxShape.circle,
                                    border: Border.all(color: task.isCompleted ? const Color(0xFF00C853) : task.typeColor, width: 2),
                                    color: task.isCompleted ? const Color(0xFF00C853) : Colors.transparent,
                                  ),
                                  alignment: Alignment.center,
                                  child: Icon(
                                    task.isCompleted ? Icons.check : task.typeIcon,
                                    size: 12.r,
                                    color: task.isCompleted ? Colors.white : task.typeColor,
                                  ),
                                ),
                                SizedBox(width: 8.w),
                                if (task.hasAlarm)
                                  Icon(Icons.notifications, size: 16.r, color: task.isCompleted ? Colors.grey[400] : Colors.orange),
                              ],
                            ),
                          ],
                        ),
                      ),

                      // 删除按钮
                      IconButton(
                        onPressed: () => _showDeleteDialog(task),
                        icon: Icon(Icons.delete_outline, size: 20.r, color: Colors.grey[400]),
                        padding: EdgeInsets.zero,
                        constraints: const BoxConstraints(),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          )
        ],
      );
    }
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.r),
        boxShadow: [
          BoxShadow(color: Colors.black.withOpacity(0.04), blurRadius: 6, offset: const Offset(0, 2)),
        ],
      ),
      child: Material(
        color: Colors.transparent,
        borderRadius: BorderRadius.circular(12.r),
        child: InkWell(
          borderRadius: BorderRadius.circular(12.r),
          onTap: () => logic.toggleTaskCompletion(task.id),
          child: Padding(
            padding: EdgeInsets.all(12.r),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 左侧：日期与时间
                Container(
                  width: 86.w,
                  padding: EdgeInsets.symmetric(vertical: 4.h),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        dateStr,
                        style: TextStyle(fontSize: 12.sp, color: Colors.grey[600]),
                      ),
                      SizedBox(height: 4.h),
                      Row(
                        children: [
                          Icon(Icons.access_time, size: 14.r, color: Colors.grey[500]),
                          SizedBox(width: 4.w),
                          Text(
                            timeStr,
                            style: TextStyle(fontSize: 12.sp, color: Colors.grey[500]),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),

                // 右侧：标题、类型标签、备注与状态
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          // 标题
                          Expanded(
                            child: Text(
                              task.title,
                              style: TextStyle(
                                fontSize: 16.sp,
                                fontWeight: FontWeight.w500,
                                color: task.isCompleted ? Colors.grey[500] : Colors.black,
                                decoration: task.isCompleted ? TextDecoration.lineThrough : TextDecoration.none,
                              ),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                          SizedBox(width: 8.w),
                          // 类型标签
                          Container(
                            padding: EdgeInsets.symmetric(horizontal: 6.w, vertical: 2.h),
                            decoration: BoxDecoration(
                              color: task.typeColor.withOpacity(0.1),
                              borderRadius: BorderRadius.circular(4.r),
                              border: Border.all(color: task.typeColor.withOpacity(0.3)),
                            ),
                            child: Text(
                              task.typeName,
                              style: TextStyle(fontSize: 10.sp, color: task.typeColor, fontWeight: FontWeight.bold),
                            ),
                          ),
                        ],
                      ),
                      if (task.note.isNotEmpty) ...[
                        SizedBox(height: 4.h),
                        Text(
                          task.note,
                          style: TextStyle(
                            fontSize: 14.sp,
                            color: task.isCompleted ? Colors.grey[400] : Colors.grey[600],
                            decoration: task.isCompleted ? TextDecoration.lineThrough : TextDecoration.none,
                          ),
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ],
                      SizedBox(height: 6.h),
                      Row(
                        children: [
                          // 完成状态图标
                          Container(
                            width: 20.r,
                            height: 20.r,
                            decoration: BoxDecoration(
                              shape: BoxShape.circle,
                              border: Border.all(color: task.isCompleted ? const Color(0xFF00C853) : task.typeColor, width: 2),
                              color: task.isCompleted ? const Color(0xFF00C853) : Colors.transparent,
                            ),
                            alignment: Alignment.center,
                            child: Icon(
                              task.isCompleted ? Icons.check : task.typeIcon,
                              size: 12.r,
                              color: task.isCompleted ? Colors.white : task.typeColor,
                            ),
                          ),
                          SizedBox(width: 8.w),
                          if (task.hasAlarm)
                            Icon(Icons.notifications, size: 16.r, color: task.isCompleted ? Colors.grey[400] : Colors.orange),
                        ],
                      ),
                    ],
                  ),
                ),

                // 删除按钮
                IconButton(
                  onPressed: () => _showDeleteDialog(task),
                  icon: Icon(Icons.delete_outline, size: 20.r, color: Colors.grey[400]),
                  padding: EdgeInsets.zero,
                  constraints: const BoxConstraints(),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 构建日历容器
  Widget _buildCalendarContainer() {
    return Expanded(
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 20.w),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(24.r),
        ),
        child: Column(
          children: [
            _buildWeekdayHeader(),
            Expanded(
              child: _buildCalendarGrid(),
            ),
          ],
        ),
      ),
    );
  }

  // 构建星期头部
  Widget _buildWeekdayHeader() {
    final List<String> weekdays = ['日', '一', '二', '三', '四', '五', '六'];
    return Container(
      padding: EdgeInsets.symmetric(vertical: 16.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: weekdays.map((day) {
          return Container(
            width: 40.w,
            alignment: Alignment.center,
            child: Text(
              day,
              style: TextStyle(
                fontSize: 16.sp,
                fontWeight: FontWeight.bold,
                color: Colors.black54,
              ),
            ),
          );
        }).toList(),
      ),
    );
  }

  // 构建日历网格
  Widget _buildCalendarGrid() {
    final days = logic.daysInMonth;
    return GridView.builder(
      padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 8.h),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 7,
        childAspectRatio: 0.8,
      ),
      itemCount: days.length,
      itemBuilder: (context, index) {
        final day = days[index];
        final isCurrentMonth = day.month == logic.currentMonth.value.month;
        final isSelected = day.day == logic.selectedDate.value.day &&
                          day.month == logic.selectedDate.value.month &&
                          day.year == logic.selectedDate.value.year;
        
        // 获取节日或农历信息
        final lunarInfo = logic.getFestivalOrJieqi(day);
        final isSpecialDay = lunarInfo == '国庆节' || lunarInfo == '中秋节' || lunarInfo == '重阳节';
        
        // 判断是否为特殊节日（如重阳节）
        final isHighlightedDay = day.day == 29 && day.month == 9;
        
        return GestureDetector(
          onTap: () => logic.selectDate(day),
          child: Container(
            margin: EdgeInsets.all(1.r),
            decoration: BoxDecoration(
              color: isSelected ? kAppThemeColor.withOpacity(0.1) : Colors.transparent,
              borderRadius: BorderRadius.circular(8.r),
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // 阳历日期
                Container(
                  width: 32.r,
                  height: 32.r,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: isHighlightedDay ? const Color(0xFF00C853) : (isSelected ? kAppThemeColor : Colors.transparent),
                  ),
                  child: Text(
                    '${day.day}',
                    style: TextStyle(
                      fontSize: 16.sp,
                      fontWeight: FontWeight.bold,
                      color: isHighlightedDay || isSelected 
                          ? Colors.white 
                          : isCurrentMonth 
                              ? Colors.black 
                              : Colors.black38,
                    ),
                  ),
                ),
                SizedBox(height: 4.h),
                // 农历或节日信息
                Container(
                  alignment: Alignment.center,
                  child: Text(
                    isHighlightedDay ? '重阳节' : lunarInfo,
                    style: TextStyle(
                      fontSize: 12.sp,
                      color: isSpecialDay || isHighlightedDay
                          ? Colors.red 
                          : isCurrentMonth 
                              ? Colors.black54 
                              : Colors.black26,
                    ),
                  ),
                ),
                // 底部小红点：当该日期存在记录/提醒/代办时显示
                Obx(() {
                  // 说明：
                  // - 通过逻辑层 hasItemsOnDate 判断当天是否有任何 TaskItem
                  // - 若存在，则在底部显示一个小红点作为提示
                  final hasItems = logic.hasItemsOnDate(day);
                  if (!hasItems) return const SizedBox.shrink();
                  return Container(
                    margin: EdgeInsets.only(top: 3.h),
                    width: 6.r,
                    height: 6.r,
                    decoration: BoxDecoration(
                      color: kAppColor('#FF3B30'), // 统一使用全局颜色方法，红色小圆点
                      shape: BoxShape.circle,
                    ),
                  );
                }),
              ],
            ),
          ),
        );
      },
    );
  }
  
  // 构建任务事项部分（统一处理待办事项和提醒事项）
  Widget _buildTodoSection() {
    return Obx(() {
      final tasksForDate = logic.tasksForSelectedDate;
      final pendingCount = tasksForDate.where((item) => !item.isCompleted).length;
      
      return Container(
        margin: EdgeInsets.symmetric(horizontal: 20.w, vertical: 16.h),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(24.r),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.05),
              blurRadius: 8,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: Material(
          color: Colors.transparent,
          borderRadius: BorderRadius.circular(24.r),
          child: InkWell(
            borderRadius: BorderRadius.circular(24.r),
            onTap: () => logic.toggleTodoExpanded(),
            child: Column(
              children: [
                // 待办事项头部
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 16.h),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(
                        children: [
                          Text(
                            '待办事项',
                            style: TextStyle(
                              fontSize: 16.sp,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          SizedBox(width: 10.w),
                          Container(
                            width: 24.r,
                            height: 24.r,
                            decoration: BoxDecoration(
                              color: pendingCount > 0 ? const Color(0xFF00C853) : Colors.grey[400],
                              shape: BoxShape.circle,
                            ),
                            alignment: Alignment.center,
                            child: Text(
                              '$pendingCount',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 14.sp,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                        ],
                      ),
                      Icon(
                        logic.isTodoExpanded
                            ? Icons.keyboard_arrow_up 
                            : Icons.keyboard_arrow_down,
                        color: Colors.grey,
                      ),
                    ],
                  ),
                ),
                
                // 待办事项列表（展开时显示）
                if (logic.isTodoExpanded) ...[
                  Divider(height: 1, color: Colors.grey[200]),
                  if (tasksForDate.isEmpty) ...[
                    // 空状态
                    Padding(
                      padding: EdgeInsets.symmetric(vertical: 32.h),
                      child: Column(
                        children: [
                          Icon(
                            Icons.checklist,
                            size: 48.r,
                            color: Colors.grey[300],
                          ),
                          SizedBox(height: 8.h),
                          Text(
                            '暂无任务事项',
                            style: TextStyle(
                              fontSize: 14.sp,
                              color: Colors.grey[500],
                            ),
                          ),
                          SizedBox(height: 8.h),
                          Text(
                            '点击右下角"+"按钮添加',
                            style: TextStyle(
                              fontSize: 12.sp,
                              color: Colors.grey[400],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ] else ...[
                    // 任务事项列表
                    ...tasksForDate.map((task) => _buildTaskItem(task)).toList(),
                    SizedBox(height: 8.h),
                  ],
                ],
              ],
            ),
          ),
        ),
      );
    });
  }
  
  // 构建单个任务事项（统一处理待办事项和提醒事项）
  Widget _buildTaskItem(TaskItem task) {
    final timeStr = '${task.dateTime.hour.toString().padLeft(2, '0')}:${task.dateTime.minute.toString().padLeft(2, '0')}';
    
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
      decoration: BoxDecoration(
        color: Colors.grey[50],
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Material(
        color: Colors.transparent,
        borderRadius: BorderRadius.circular(12.r),
        child: InkWell(
          borderRadius: BorderRadius.circular(12.r),
          onTap: () => logic.toggleTaskCompletion(task.id),
          child: Padding(
            padding: EdgeInsets.all(16.r),
            child: Row(
              children: [
                // 完成状态复选框
                Container(
                  width: 24.r,
                  height: 24.r,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    border: Border.all(
                      color: task.isCompleted ? const Color(0xFF00C853) : task.typeColor,
                      width: 2,
                    ),
                    color: task.isCompleted ? const Color(0xFF00C853) : Colors.transparent,
                  ),
                  child: task.isCompleted
                      ? Icon(
                          Icons.check,
                          size: 16.r,
                          color: Colors.white,
                        )
                      : Icon(
                          task.typeIcon,
                          size: 16.r,
                          color: task.typeColor,
                        ),
                ),
                SizedBox(width: 12.w),
                
                // 待办事项内容
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Text(
                            task.title,
                            style: TextStyle(
                              fontSize: 16.sp,
                              fontWeight: FontWeight.w500,
                              color: task.isCompleted ? Colors.grey[500] : Colors.black,
                              decoration: task.isCompleted ? TextDecoration.lineThrough : TextDecoration.none,
                            ),
                          ),
                          SizedBox(width: 8.w),
                          Container(
                            padding: EdgeInsets.symmetric(horizontal: 6.w, vertical: 2.h),
                            decoration: BoxDecoration(
                              color: task.typeColor.withOpacity(0.1),
                              borderRadius: BorderRadius.circular(4.r),
                              border: Border.all(color: task.typeColor.withOpacity(0.3)),
                            ),
                            child: Text(
                              task.typeName,
                              style: TextStyle(
                                fontSize: 10.sp,
                                color: task.typeColor,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                        ],
                      ),
                      if (task.note.isNotEmpty) ...[
                        SizedBox(height: 4.h),
                        Text(
                          task.note,
                          style: TextStyle(
                            fontSize: 14.sp,
                            color: task.isCompleted ? Colors.grey[400] : Colors.grey[600],
                            decoration: task.isCompleted ? TextDecoration.lineThrough : TextDecoration.none,
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ],
                      SizedBox(height: 4.h),
                      Row(
                        children: [
                          Text(
                            timeStr,
                            style: TextStyle(
                              fontSize: 12.sp,
                              color: task.isCompleted ? Colors.grey[400] : Colors.grey[500],
                            ),
                          ),
                          SizedBox(width: 8.w),
                          if (task.hasAlarm)
                            Icon(
                              Icons.notifications,
                              size: 14.r,
                              color: task.isCompleted ? Colors.grey[400] : Colors.orange,
                            ),
                        ],
                      ),
                    ],
                  ),
                ),
                
                // 删除按钮
                IconButton(
                  onPressed: () => _showDeleteDialog(task),
                  icon: Icon(
                    Icons.delete_outline,
                    size: 20.r,
                    color: Colors.grey[400],
                  ),
                  padding: EdgeInsets.zero,
                  constraints: const BoxConstraints(),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
  
  // 显示删除确认对话框
  void _showDeleteDialog(TaskItem task) {
    AdsUtils.showInterstitialAd();
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('删除${task.typeName}'),
        content: Text('确定要删除这条${task.typeName}吗？此操作不可恢复。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              logic.deleteTask(task.id);
              Navigator.pop(context);
            },
            child: const Text('删除'),
          ),
        ],
      ),
    );
  }
}